<?php
declare (strict_types = 1);

namespace app\mobile\controller;
use think\facade\Db;

use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
class Wechat extends \app\mobile\Base
{
  public function customer()
  {
    $appid = input('appid');
    $post = input('post.');
    $mini = getSettingType('小程序');
    if ($appid != $mini['mini_app_id']) return;
    $config = [
      'app_id' => $appid,
      'secret' => $mini['mini_app_secret'],
      'token' => $mini['mini_token'],
      'aes_key' => $mini['mini_aes_key'],
      'response_type' => 'array',
      'log' => [
        'default' => 'dev', // 默认使用的 channel，生产环境可以改为下面的 prod
        'channels' => [
            // 测试环境
            'dev' => [
                'driver' => 'single',
                'path' => './easywechat.log',
                'level' => 'debug',
            ],
            // 生产环境
            'prod' => [
                'driver' => 'daily',
                'path' => './easywechat.log',
                'level' => 'info',
            ],
        ],
      ],
    ];

    if (!$post) {
      $app = Factory::officialAccount($config);
      $response = $app->server->serve();
      $response->send();exit;
    }


    $app = Factory::miniProgram($config);
    $message = $app->server->getMessage();
    $MsgType = $message['MsgType'];
    $openId = $message['FromUserName'];
    $appUserName = $message['ToUserName'];
    // $this->relation([
    //   'uid'=>6135107
    // ]);
    // return;
    if ($MsgType == 'event') {
      //客服进入会话事件
      $Event = $message['Event'];
      if ($Event == 'user_enter_tempsession') {
        $query_str = $message['SessionFrom'];
        parse_str($query_str,$query);
        if ($query['m'] == 'Wecaht.relation') {
          $rmsg = $this->relation($query);
          $text = new Text($rmsg);
          $app->customer_service->message($text)->to($openId)->send();
          exit();
        }
        
        
      }
    }

    $text = new Text('该功能完善中');
    $app->customer_service->message($text)->to($openId)->send();
    // $text2 = new Text('Hello world --- 2');
    // $app->customer_service->message($text2)->to($openId)->send();
    exit;

  }

  public function mpkf()
  {
    
    $appid = input('appid');
    $post = input('get.');
    $mini = getSettingType('公众号');
    if ($appid != $mini['mp_app_id']) return;
    $config = [
      'app_id' => $appid,
      'secret' => $mini['mp_app_secret'],
      'token' => $mini['mp_token'],
      'aes_key' => $mini['mp_aes_key'],
      'response_type' => 'array',
      'log' => [
        'default' => 'dev', // 默认使用的 channel，生产环境可以改为下面的 prod
        'channels' => [
            // 测试环境
            'dev' => [
                'driver' => 'single',
                'path' => './easywechat.log',
                'level' => 'debug',
            ],
            // 生产环境
            'prod' => [
                'driver' => 'daily',
                'path' => './easywechat.log',
                'level' => 'info',
            ],
        ],
      ],
    ];

    if (!$post) {
      $app = Factory::officialAccount($config);
      $response = $app->server->serve();
      $response->send();exit;
    }
    # code...
  }

  //淘宝备案
  public function relation($query = array())
  {
    $uid = $query['uid'];
    $user = Db::name('user')->where('id',$uid)->find();
    if ($user['relation_id']) {
      return false;
    }

    $tb = new \app\common\TaobaoApi();
    //拼接备案网址
    $union = getSettingType('饿了么');
    $url = "https://mos.m.taobao.com/inviter/register?inviterCode=".$union['ele_inviter_code']."&src=pub&app=common&rtag=".$uid;

    //先 生成口令
    $r = $tb->get('taobao.tbk.tpwd.create',[
      'url'=>$url,
      'text'=>$uid,
    ]);
    if (isset($r['error_response'])) {
      return $r['error_response']['sub_msg'];
    }
    $data = $r['tbk_tpwd_create_response']['data'];
    $user = Db::name('user')->where('id',$user['id'])->update([
      'relation_pwd'=>$data['model'],
    ]);
    return $data['model'];
    
  }
}